/*
 * www.acooly.cn Inc.
 * Copyright (c) 2018 All Rights Reserved
 */

/*
 * 修订记录:
 * zhike@acooly.cn 2018-01-31 16:37 创建
 */
package com.acooly.module.openapi.client.provider.shengpay.notify;


import com.acooly.core.common.exception.BusinessException;
import com.acooly.core.common.web.servlet.AbstractSpringServlet;
import com.acooly.core.utils.Servlets;
import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.notify.NotifyHandlerDispatcher;
import com.acooly.module.openapi.client.provider.shengpay.OpenAPIClientShengpayProperties;
import com.acooly.module.openapi.client.provider.shengpay.ShengpayConstants;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhike 2018-01-31 16:37
 */
@Slf4j
public class ShengpayApiServiceClientServlet extends AbstractSpringServlet {

    private NotifyHandlerDispatcher notifyHandlerDispatcher;

    private static final int SUCCESS_RESPONSE_CODE = 200;
    private static final String SUCCESS_RESPONSE_BODY = "SUCCESS";
    private static final String FAILED_RESPONSE_BODY = "SUCCESS";
    private static final String DEFAULT_NOTIFY_DISPATCHER_BEAN_NAME = "clientNotifyHandlerDispatcher";

    public static final String SUCCESS_RESPONSE_CODE_KEY = "success_response_code";
    public static final String SUCCESS_RESPONSE_BODY_KEY = "success_response_body";
    public static final String NOTIFY_DISPATCHER_BEAN_NAME_KEY = "NOTIFY_DISPATCHER_BEAN_NAME_KEY";
    @Autowired
    private OpenAPIClientShengpayProperties openAPIClientYipayProperties;

    @Override
    public void doService(HttpServletRequest request, HttpServletResponse response) {
        String resultJson = "OK";
        try {
            StringBuilder stringBuilder = new StringBuilder();
            InputStream inputStream = request.getInputStream();
            BufferedReader bufferedReader = null;
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
            if(Strings.isBlank(stringBuilder.toString())) {
                throw new BusinessException("异步通知报文为空");
            }
            log.info("Yipay异步通知: {}",stringBuilder.toString());
            Map<String, String> notifyData = Maps.newHashMap();
            notifyData.put(ShengpayConstants.REQUEST_PARAM_NAME,stringBuilder.toString());
            setSign(notifyData,stringBuilder.toString());
            String requestUrl = Servlets.getRequestPath(request);
            notifyHandlerDispatcher.dispatch(requestUrl, notifyData);
            response.setStatus(SUCCESS_RESPONSE_CODE);
            Servlets.writeResponse(response, resultJson, null);
        } catch (Exception e) {
            resultJson="FAILED";
            Servlets.writeResponse(response,  resultJson, null);
        }
    }
    /**
     * 处理通知参数
     */
    private void setSign(Map<String, String> notifyData,String notifyStr){
        Map<String, String>  notifyMap=getUrlParams(notifyStr);
        //组装响应json 保持格式与支付一致。{"returnCode":"SUCCESS","returnMessage":"请求正常完成"}
        JSONObject resJson=JSONObject.parseObject(JSONObject.toJSONString(notifyMap));
//        resJson.put("returnCode",notifyMap.get("TransStatus"));
//        resJson.put("returnMessage",notifyMap.get("ErrorCode")+":"+notifyMap.get("ErrorMsg"));
        log.info("盛支付通知组装的报文----{}",resJson.toString());
        notifyData.put(ShengpayConstants.NOTIFY_DATA_JSON,resJson.toString());
    }
    /**
     * 将url参数转换成map
     * @param param aa=11&bb=22&cc=33
     * @return
     */
    public static Map<String, String> getUrlParams(String param) {
        Map<String, String> map = new HashMap<String, String>(0);
        if (StringUtils.isBlank(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }

    @Override
    public void doInit() {
        super.doInit();
        notifyHandlerDispatcher = getBean(getDispatcherBeanName(), NotifyHandlerDispatcher.class);
    }

    @Override
    public void destroy() {
        log.info("Yipay异步通知接受Filter销毁");
    }

    protected String getDispatcherBeanName() {
        String beanName = getInitParameter(NOTIFY_DISPATCHER_BEAN_NAME_KEY);
        if (Strings.isBlank(beanName)) {
            beanName = DEFAULT_NOTIFY_DISPATCHER_BEAN_NAME;
        }
        return beanName;
    }
}
